package com.jtbd.service.auth;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jtbd.config.CustomAuthentication;
import com.jtbd.constants.ResponseCodeEnum;
import com.jtbd.domain.UserInfo;
import com.jtbd.domain.UserRoleRelation;
import com.jtbd.dto.UserAuthDetailsEntity;
import com.jtbd.exceptions.SystemException;
import com.jtbd.mapper.UserInfoMapper;
import com.jtbd.mapper.UserRoleRelationMapper;
import com.jtbd.service.UserAuthService;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户认证相关的service
 */
@Service
public class UserAuthServiceImpl implements UserAuthService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private UserRoleRelationMapper userRoleRelationMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 解析用户名 用户唯一判断逻辑为手机号+用户类型
        String[] usernameArr = CustomAuthentication.splitUsername(username);
        if (!ObjectUtils.isEmpty(usernameArr) && usernameArr.length == 2) {
            String phone = usernameArr[0];
            Integer userType = Integer.parseInt(usernameArr[1]);
            LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserInfo::getPhone, phone);
            queryWrapper.eq(UserInfo::getUserType, userType);
            UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
            if (userInfo == null) {
                throw new SystemException(ResponseCodeEnum.ERROR.getCode(), "用户不存在");
            }
            LambdaQueryWrapper<UserRoleRelation> roleRelationLambdaQueryWrapper = new LambdaQueryWrapper<>();
            roleRelationLambdaQueryWrapper.eq(UserRoleRelation::getUserId, userInfo.getId());
            List<UserRoleRelation> userRoleRelations = userRoleRelationMapper.selectList(roleRelationLambdaQueryWrapper);
            String roleIds = null;
            if (!ObjectUtils.isEmpty(userRoleRelations)) {
                roleIds = userRoleRelations.stream().map(item -> String.valueOf(item.getRoleId())).collect(Collectors.joining(","));
            }
            return new UserAuthDetailsEntity(userInfo.getId(), userInfo.getPhone(), userInfo.getUserType(), userInfo.getPassword(), roleIds);
        }
        return null;
    }
}
